#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Developer Console."""

import cgi
import logging
import os

from base import BaseHandler
import error
from google.appengine.api import images
from google.appengine.api.datastore_errors import BadValueError
from google.appengine.api.images import NotImageError
from google.appengine.ext import db
import jinja2
from lib import authn
from lib import utils
from lib.loggable import loggable
import model

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.2'
__status__ = 'Prototype'

jinja_environment = jinja2.Environment(
  loader=jinja2.FileSystemLoader(
    os.path.join(os.path.dirname(__file__),'templates/')))

logging.getLogger().setLevel(logging.DEBUG)


class DeveloperHandler(BaseHandler):
  """Handles requests to the Developer Console."""

  @authn.login_required()
  @loggable('developer')
  def get(self):
    """Handles GET requests for displaying the Developer Console."""

    user = self.user

    application_list_empty = user.application_list.get()

    values = {
        'user': user,
        'application_list': user.application_list,
        'application_list_empty': application_list_empty
    }
    template = jinja_environment.get_template('developer.html')
    self.response.out.write(template.render(values))

  @authn.login_required()
  @loggable('create application')
  def post(self):
    """Handles POST requests to register applications at Developer Console."""

    user = self.user

    name = cgi.escape(self.request.get('name'))
    client_id = cgi.escape(self.request.get('client_id'))
    icon = self.request.get('icon')
    url = cgi.escape(self.request.get('url'))

    if self._app_exists(client_id):
      error.handle_error(self, msg=
                         'There already seems to be a client with the'
                         'provided client_id',
                         url='/developer',
                         url_name='developer page')
      return

    try:
      new_app = model.Application(
          id=utils.random(),
          name=name,
          client_id=client_id,
          icon=db.Blob(images.resize(icon, 64, 64)),
          url=url,
          user=user)
      new_app.put()
    except BadValueError:
      error.handle_error(self, msg=
                         'You have not provided correct information about your'
                         ' application. Some fields are missing?',
                         url='/developer',
                         url_name='developer page')
      return
    except NotImageError:
      error.handle_error(self, msg='Have you provided an icon for '
                         'your application?',
                         url='/developer',
                         url_name='developer page')
      return

    logging.debug('stored new application for this user')

    self.redirect('/developer')

  def _app_exists(self, client_id):
    app = model.Application.all().filter('client_id = ', client_id).get()
    return app is not None


class DeveloperRemoveAppHandler(BaseHandler):
  """Handles requests to delete registered applications."""

  @authn.login_required()
  @loggable('delete application')
  def post(self):
    """Handles POST requests to delete registered applications."""

    application = db.get(self.request.get('app_id'))
    if application and application.user.email == self.user.email:
      application.delete()
      logging.debug('application deleted successfully')
    else:
      logging.error('application not found or associated with a '
                    'different user')
      error.handle_error(self)
      return
    self.redirect('/developer')
